/**
 * 
 */
package com.mobi.Survey;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.appbucks.sdk.AppBucksAPI;
import com.mobi.Survey.controller.SurveyPojo;
import com.mobi.Survey.controller.SurveysJsonParser;
import com.mobi.Survey.controller.User;
import com.mobi.Survey.controller.User.Image;
import com.mobi.Survey.utils.Helper;

/**
 * 
 * <p>
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * LoginScreen.java This screen will prompt user to enter user name and password
 * 
 */
public class LoginScreen extends AbstractScreen
{

	private TextView txtErrorLogin;

	private EditText editPassword;

	private EditText editUserId;

	private static final String KEY_USER_ID = "0x1";

	private static final String KEY_USER_PSW = "0x2";

	private static final String KEY_LAYOUT_NAME = "0x3";

	private static final String KEY_LAYOUT_TYPE = "0x4";

	private static final String KEY_SHOW_ADS = "0x5";

	private static final String KEY_LIST_IMAGE = "0x6";

	private static final String KEY_DETAIL_IMAGE = "0x7";

	private static final String KEY_LIST_IMAGE_SIZE = "0x8";

	private static final String KEY_DETAIL_IMAGE_SIZE = "0x9";

	private static final String SHARED_PREF = "LoginScreen";

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);

		SharedPreferences prefs = this.getSharedPreferences(SHARED_PREF,
				Context.MODE_PRIVATE);

		String userId = prefs.getString(KEY_USER_ID, "").trim();

		if (null != userId && userId.length() > 0)
		{

			editUserId.setText(userId);
		}
		String psw = prefs.getString(KEY_USER_PSW, null);
		if (null != psw && psw.length() > 0)
		{
			editPassword.setText(psw);
		}
	}

	public void onClick(View view)
	{
		switch (view.getId())
		{
		case R.id.btnLogin:
			new LongTask().execute();
			break;

		case R.id.btnSkip:
			onSkipClick();
			populateUserBitmaps();
			populateContextBitmaps();
			break;
		}
	}

	private void onSkipClick()
	{
		SharedPreferences prefs = this.getSharedPreferences(SHARED_PREF,
				Context.MODE_PRIVATE);
		User.getInstance().setLayoutName(
				prefs.getString(KEY_LAYOUT_NAME, "Survey Form"));

		User.getInstance().setLayoutType(prefs.getInt(KEY_LAYOUT_TYPE, 0));

		String detailImageUrl = prefs.getString(KEY_DETAIL_IMAGE, null);
		String listImageUrl = prefs.getString(KEY_LIST_IMAGE, null);

		float detailImageSize = prefs.getFloat(KEY_DETAIL_IMAGE_SIZE, 1);
		float listImageSize = prefs.getFloat(KEY_LIST_IMAGE_SIZE, 1);

		if (null != detailImageUrl)
		{
			User.getInstance().setDetailImage(
					new Image(detailImageUrl, detailImageSize));

		}
		if (null != listImageUrl)
		{
			User.getInstance().setListImage(
					new Image(listImageUrl, listImageSize));
		}

		User.getInstance().setShowAds(true);
		initeAppBuckSdk(User.getInstance());
		switchScreenTo(SurveyListScreen.class);

	}

	private void populateContextBitmaps()
	{

		String icCorrectAnswer = Helper
				.getHashNameFromUrl(getString(R.string.ic_correct_answer_url))
				+ "";
		String icInfo = Helper
				.getHashNameFromUrl(getString(R.string.ic_info_url)) + "";
		String icGraph = Helper
				.getHashNameFromUrl(getString(R.string.ic_graph_url)) + "";

		icCorrectAnswer = Helper.getTempFile(icCorrectAnswer);
		icInfo = Helper.getTempFile(icInfo);
		icGraph = Helper.getTempFile(icGraph);

		if (new File(icCorrectAnswer).exists())
		{
			User.getInstance().getIconCorrectAnswer()
					.setBitmap(Helper.decode70x70(icCorrectAnswer, 1));
		} else
		{

		}
		if (new File(icCorrectAnswer).exists())
		{
			User.getInstance().getIconInfo()
					.setBitmap(Helper.decode70x70(icInfo, 1));
		} else
		{

		}
		if (new File(icCorrectAnswer).exists())
		{
			User.getInstance().getIconGraph()
					.setBitmap(Helper.decode70x70(icGraph, 1));
		} else
		{

		}

	}

	@Override
	protected void initUiVars()
	{
		txtErrorLogin = (TextView) findViewById(R.id.txtErrorLogin);
		editPassword = (EditText) findViewById(R.id.editPassword);
		editUserId = (EditText) findViewById(R.id.editUserId);

	}

	@Override
	protected int getLayoutId()
	{

		return R.layout.login;
	}

	@Override
	protected void onRelease()
	{

	}

	public void onBackPressed()
	{

		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);

	}

	private void populateUserBitmaps()
	{
		try
		{
			String imageUrl = User.getInstance().getListImage().getUrl();
			if (null != imageUrl && imageUrl.length() > 0)
			{

				String outputfile = Helper.getTempFile(Helper
						.getHashNameFromUrl(imageUrl) + "");
				if (!new File(outputfile).exists())
					Helper.downloadFile(imageUrl, outputfile);

				User.getInstance().getListImage()
						.setBitmap(Helper.decode(outputfile, 3));
			}

			imageUrl = User.getInstance().getDetailImage().getUrl();
			if (null != imageUrl && imageUrl.length() > 0)
			{

				String outputfile = Helper.getTempFile(Helper
						.getHashNameFromUrl(imageUrl) + "");
				if (!new File(outputfile).exists())
					Helper.downloadFile(imageUrl, outputfile);

				User.getInstance().getDetailImage()
						.setBitmap(BitmapFactory.decodeFile(outputfile));
			}
		} catch (IOException e)
		{
			Log.e(LoginScreen.class.getSimpleName(),
					"Download Error: " + e.getMessage());
		}
	}

	/**
	 * Download surveys in background after downloading survey we will delete
	 * old surveys and insert new records
	 * 
	 * @author Yahya Arshad
	 * 
	 */
	private class LongTask extends AsyncTask<String, Integer, Integer>
	{
		private final int LOGIN_ERROR = 0;

		private final int SWITCH_SCREEN = 1;

		private final int NO_INTERNET_CONNECTION = 2;

		private final int CONNECT_ERROR = 3;

		private String userId;

		private String psw;

		ProgressDialog progressDialog = null;

		protected Integer doInBackground(String... params)
		{

			if (Helper.isNetworkAvailable(LoginScreen.this
					.getApplicationContext()) && !isCancelled())
			{

				try
				{
					String loginUrl = getString(R.string.dev_login_ws)
							+ "userId=" + userId + "&userPassword=" + psw;

					String surveyUrl = getString(R.string.dev_survey_data_ws)
							+ "userId=" + userId + "&userPassword=" + psw;

					InputStream loginResponse = Helper
							.performGetOperationI(loginUrl);

					// Login attempt
					if (SurveysJsonParser.isUser(loginResponse))
					{
						publishProgress(30);

						// if successfully login get surveys

						InputStream surveyResponse = Helper
								.performGetOperationI(surveyUrl);
						// String surveyResponse = Helper
						// .performGetOperation(surveyUrl);
						List<SurveyPojo> surveys = SurveysJsonParser
								.parseSurveysWithJacksonStreaming(surveyResponse);

						// got some surveys delete previous and insert new
						// surveys
						if (surveys.size() > 0)
						{
							SurveyPojo.deleteAll(getApplicationContext());
							publishProgress(40);
							SurveyPojo.commitAll(getApplicationContext(),
									surveys);

						}

						if (!new File(
								Helper.getTempFileFromUrl(getString(R.string.ic_info_url)))
								.exists())
						{
							Helper.downloadFile(
									getString(R.string.ic_info_url),
									Helper.getTempFileFromUrl(getString(R.string.ic_info_url)));
						}

						if (!new File(
								Helper.getTempFileFromUrl(getString(R.string.ic_correct_answer_url)))
								.exists())
						{
							Helper.downloadFile(
									getString(R.string.ic_correct_answer_url),
									Helper.getTempFileFromUrl(getString(R.string.ic_correct_answer_url)));
						}

						if (!new File(
								Helper.getTempFileFromUrl(getString(R.string.ic_graph_url)))
								.exists())
						{
							Helper.downloadFile(
									getString(R.string.ic_graph_url),
									Helper.getTempFileFromUrl(getString(R.string.ic_graph_url)));
						}
						populateUserBitmaps();
						populateContextBitmaps();

						return SWITCH_SCREEN;

					} else
					{
						return LOGIN_ERROR;
					}

				} catch (IOException e)
				{
					return CONNECT_ERROR;
				} catch (Exception e)
				{

					return LOGIN_ERROR;
				}

			} else
			{
				return NO_INTERNET_CONNECTION;
			}

		}

		@Override
		protected void onProgressUpdate(Integer... values)
		{

			super.onProgressUpdate(values);

			if (values[0] == 30)
			{
				progressDialog.setMessage(Messages.DOWNLOADING_SURVEYS);
			}
			if (values[0] == 40)
			{
				progressDialog.setMessage(Messages.UPDATING_DATABASE);
			}
		}

		protected void onPostExecute(Integer result)
		{

			super.onPostExecute(result);

			progressDialog.dismiss();
			progressDialog = null;

			switch (result)
			{
			case LOGIN_ERROR:
				txtErrorLogin
						.setText(getString(R.string.error_invalid_user_id_or_password));
				txtErrorLogin.setVisibility(View.VISIBLE);
				break;

			case CONNECT_ERROR:

				txtErrorLogin.setText(Messages.CONNECT_ERROR);
				txtErrorLogin.setVisibility(View.VISIBLE);
				break;

			case SWITCH_SCREEN:

				SharedPreferences prefs = LoginScreen.this
						.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);

				prefs.edit()
						.putString(KEY_LAYOUT_NAME,
								User.getInstance().getLayoutName())
						.putInt(KEY_LAYOUT_TYPE,
								User.getInstance().getLayoutType())
						.putBoolean(KEY_SHOW_ADS,
								User.getInstance().isShowAds())
						.putString(KEY_LIST_IMAGE,
								User.getInstance().getListImage().getUrl())
						.putString(KEY_DETAIL_IMAGE,
								User.getInstance().getDetailImage().getUrl())
						.putFloat(
								KEY_LIST_IMAGE_SIZE,
								User.getInstance().getListImage()
										.getPercentHeight())
						.putFloat(
								KEY_DETAIL_IMAGE_SIZE,
								User.getInstance().getDetailImage()
										.getPercentHeight()).commit();

				initeAppBuckSdk(User.getInstance());
				switchScreenTo(SurveyListScreen.class);
				break;
			case NO_INTERNET_CONNECTION:
				txtErrorLogin.setText(Messages.NO_INTERNET_CONNECTION);
				txtErrorLogin.setVisibility(View.VISIBLE);
				break;

			}

		}

		protected void onPreExecute()
		{

			super.onPreExecute();
			// show progress dialogue

			txtErrorLogin.setVisibility(View.INVISIBLE);

			userId = editUserId.getText().toString().trim();
			psw = editPassword.getText().toString();

			if (userId.length() == 0)
			{

				cancel(true);
				return;
			}

			progressDialog = ProgressDialog.show(LoginScreen.this, "",
					Messages.LOGGIN_IN);

			// put user email and psw in shared preferences
			SharedPreferences prefs = LoginScreen.this.getSharedPreferences(
					SHARED_PREF, Context.MODE_PRIVATE);
			prefs.edit().putString(KEY_USER_ID, userId)
					.putString(KEY_USER_PSW, psw).commit();

		}

	}

	private final void initeAppBuckSdk(User user)
	{
		// APP BUCK CONFIGURATION PARAMS MUST Turn Off Test Mode during
		// deployment in Play store
		if (user.isShowAds())
		{
			final String APP_BUCK_KEY = "7634b39f-ccb3-445c-8ca2-8968dcf1da02";
			final long APP_BUCK_APPID = 1982147224;

			AppBucksAPI.initialize(LoginScreen.this,
					getString(R.string.app_name), R.drawable.icon,
					APP_BUCK_APPID, APP_BUCK_KEY,
					Boolean.valueOf(getString(R.string.APP_TEST_MODE)), null,

					null);
		}

	}
}